package com.example.forum.controller;

import com.example.forum.common.AppResult;
import com.example.forum.common.ResultCode;
import com.example.forum.config.ContentConfig;
import com.example.forum.exception.ApplicationException;
import com.example.forum.model.Message;
import com.example.forum.model.User;
import com.example.forum.service.imp.MessageService;
import com.example.forum.service.imp.UserServiceImp;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import lombok.NonNull;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Slf4j
@RestController
@RequestMapping("/message")
public class MessageController {
    @Autowired
    private UserServiceImp userServiceImp;

    @Autowired
    private MessageService messageService;

    @RequestMapping(value = "/send",method = RequestMethod.POST)
    public AppResult send (HttpServletRequest request,
                           @RequestParam("receiveUserId") @NonNull Long receiveUserId,
                           @RequestParam("content") @NonNull String content) {
        //判断当前登录用户的状态
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(ContentConfig.USER_SESSION);

        if(user == null || user.getDeleteState() == 1){
            log.warn(ResultCode.FAILED_USER_NOT_EXISTS.toString());

            throw new ApplicationException(AppResult.fail(ResultCode.FAILED_USER_NOT_EXISTS));
        }
        if(user.getState() == 1){
            log.warn(ResultCode.FAILED_USER_BANNED.toString());
            throw new ApplicationException(AppResult.fail(ResultCode.FAILED_USER_BANNED));
        }

        //不能给自己发送
        if(receiveUserId == user.getId()){
            return AppResult.fail("不能给自己发送私信");
        }
        //校验接收者是否存在
        User recevieUser = userServiceImp.selectById(receiveUserId);
        if(recevieUser == null || recevieUser.getDeleteState() == 1){
            // 返回接收者状态不正常
            return AppResult.fail("接收者状态异常");
        }

        //构造对象
        Message message = new Message();
        message.setReceiveUserId(receiveUserId);
        message.setPostUserId(user.getId());
        message.setContent(content);

        messageService.create(message);
        return AppResult.success("发送成功");
    }
    @GetMapping("/getUnreadCount")
    public AppResult selectUnreadCount(HttpServletRequest request){
        //这里的登录者就是接收者
        HttpSession session = request.getSession(false);

        User user = (User) session.getAttribute(ContentConfig.USER_SESSION);

        if(user == null || user.getDeleteState() == 1){
            return AppResult.fail(ResultCode.FAILED_USER_NOT_EXISTS);
        }

        //调用服务层
        int result = messageService.selectUnreadCount(user.getId());
        return AppResult.success(result);

    }
    @RequestMapping(value = "/getAll",method = RequestMethod.GET)
    public AppResult<List<Message>>  selectByReceiveId(HttpServletRequest request){
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(ContentConfig.USER_SESSION);
        // 2. 调用Service
        List<Message> messages = messageService.selectByReceiveId(user.getId());
        // 3. 返回结果
        return AppResult.success(messages);
    }

    @RequestMapping(value = "/markRead" , method = RequestMethod.POST)
    public AppResult updateStateById(HttpServletRequest request,
                                     @RequestParam("id") Long id){

        //校验私信是否存在
        Message existMessage = messageService.selectById(id);
        if(existMessage == null || existMessage.getDeleteState() == 1 ){
            log.warn(ResultCode.FAILED_MESSAGE_NOT_EXISTS.toString());

            throw new ApplicationException(AppResult.fail(ResultCode.FAILED_MESSAGE_NOT_EXISTS));
        }

        //判断接收者是否是自己
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(ContentConfig.USER_SESSION);

        if(user.getId() != existMessage.getReceiveUserId()){
            return AppResult.fail(ResultCode.FAILED_FORBIDDEN);
        }

        messageService.updateStateById(id,(byte) 1);
        return AppResult.success();

    }

    @PostMapping("/reply")
    public AppResult reply (HttpServletRequest request,
                             @RequestParam("repliedId") @NonNull Long repliedId,
                             @RequestParam("content") @NonNull String content) {

        // 校验当前登录用户的状态
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(ContentConfig.USER_SESSION);
        if (user.getState() == 1) {
            // 返回错误描述
            return AppResult.fail(ResultCode.FAILED_USER_BANNED);
        }

        // 校验要回复的站内信状态
        Message existsMessage = messageService.selectById(repliedId);
        if (existsMessage == null || existsMessage.getDeleteState() == 1) {
            // 返回错误描述
            return AppResult.fail(ResultCode.FAILED_MESSAGE_NOT_EXISTS);
        }
        // 不能给自己回复
        if (user.getId() == existsMessage.getPostUserId()) {
            // 返回错误描述
            return AppResult.fail("不能回复自己的站内信");
        }

        //构造更新
        Message message = new Message();
        message.setReceiveUserId(existsMessage.getPostUserId());
        message.setPostUserId(user.getId());
        message.setContent(content);

        messageService.reply(repliedId,message);

        return AppResult.success();

    }

}
